var express = require('express');
var router = express.Router();


// 加载db数据库文件
let db = require('../model/db');


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});

// 首页
router.get('/index', async (req, res) => {
  let sql = `select * from stu_username`
  let [err, data] = await db.query(sql);
  if (err) {
    res.send({
      "code": "400",
      "msg": "查询失败"
    })
  } else {
    res.cookie('dat',data)
    res.send({
      "code": "200",
      "msg": "查询成功",
      data: data
    })
  }
})
router.post('/index',async (req,res)=>{
  let {ids} = req.body;
  // console.log(ids);
  let sql = `select * from stu_username where id=${ids}`;
  let [err,data] = await db.query(sql);
  if(err){
    res.send({ "code": "400", "msg": "查询失败" })
  } else{
    res.cookie('dat1',data);
    res.send({ "code": "200", "msg": "查询成功", data:data})
  }
})

// 修改
router.get('/edit', async (req, res) => {
  let sql = `select * from stu_username where id=${req.cookies.dat1[0].id}`;
  let [err,data] = await db.query(sql);
  if(err){
    res.send({ "code": "400", "msg": "查询失败" })
  } else{
    res.send({ "code": "200", "msg": "查询成功", data:data})
  }
})

router.post('/edit',async (req,res) =>{
  let { user, sex, age, qq, id } = req.body;
  let sql = `update stu_username set name="${user}",sex="${sex}",age=${age},qqemail="${qq}" where id=${id}`
  let [err,data] = await db.query(sql);
  if(err){
    res.send({ "code": "200", "msg": "修改失败" });
  } else{
    res.send({ "code": "400", "msg": "修改成功" });
  }
})

// 添加
router.post("/add", async (req,res)=>{
  let {user,sex,age,qq} = req.body;
  console.log(user,sex,age,qq);
  let u = req.cookies.dat.findIndex((item)=>{
    return item.qqemail == qq;
  })
  if(u == -1){
    let sql = `insert into stu_username (name,sex,age,qqemail) value ("${user}","${sex}",${age},"${qq}")`;
    let [err,data] = await db.query(sql);
    res.send({ "code": "200", "msg": "该邮箱可以注册" });
  } else{
    res.send({ "code": "400", "msg": "该邮箱已被占用" });
  }
})

// 删除
router.post('/del',async (req,res)=>{
  let {ids} = req.body;
  console.log(ids);
  let sql = `delete from stu_username where id=${ids}`;
  let [err,data] = await db.query(sql);
  if(err){
    res.send({ "code": "400", "msg": "删除失败" })
  } else{
    res.send({ "code": "200", "msg": "删除成功" })
  }
})




module.exports = router;